<template>
  <div class="app-pending" style="margin: 0 !important;">
    <div class="top-container">
      <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline" style="display: block !important;">
        <el-form-item label="后台单号" style="margin-bottom: 15px!important;">
          <el-input v-model.trim="formInline.xmbzNo" clearable size="medium" placeholder="后台单号"></el-input>
        </el-form-item>
        <el-form-item label="平台单号" style="margin-bottom: 15px!important;">
          <el-input v-model.trim="formInline.platformOrderId" clearable size="medium" placeholder="平台单号"></el-input>
        </el-form-item>
        <!-- <el-form-item label="城市">
          <el-input v-model="formInline.platformOrderId" size="medium" placeholder="平台单号"></el-input>
        </el-form-item> -->
        <el-form-item label="手机号" prop="receiverPhone" style="margin-bottom: 15px!important;">
          <el-input v-model.trim="formInline.receiverPhone" @input="filterPhone" clearable size="medium" placeholder="手机号" style="width: 125px"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city" style="margin-bottom: 15px!important;">
          <el-select ref="deptRef" v-model="deptName" placeholder="城市" @change="handleCity" size="medium" @keydown.native="selectBlur($event)" style="width: 100%;">
            <el-option v-for="(house,citykey) in cityselect" :key="citykey" :label="house.deptName" :value="{value:house.id,label:house.deptName}"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道类别" style="margin-bottom: 15px!important;">
          <el-select ref="channelTypeRef" v-model="formInline.channelType" @keydown.native="keydown($event)" clearable filterable size="medium" placeholder="渠道类别" style="width: 155px">
            <el-option v-for="(channelitem,channel) in channelTypellist" :key="channel" :label="channelitem.channelName"
              :value="channelitem.channelKey">
              <span :data-id="channelitem.id" style="display: inline-block;width: 150px;padding: 0 20px;margin-left: -20px;"
                @click="getchannelTypeId($event)">{{ channelitem.channelName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" style="margin-bottom: 15px!important;">
          <el-select ref="channelRef" v-model="formInline.channel" @keydown.native="keydown($event)" size="medium" filterable placeholder="渠道" style="width: 155px">
            <el-option v-for="(channelitem,channel) in channerllist" :key="channel" :label="channelitem.channelName"
              :value="channelitem.channelKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select ref="selectRef" v-model="formInline.select" placeholder="时间" size="medium" @keydown.native="selectBlur($event)" style="width: 110px;margin: 0 8px;">
            <el-option label="配送时间" value="配送时间"></el-option>
            <el-option label="下单时间" value="下单时间"></el-option>
          </el-select>
          <el-date-picker
            v-model="timeValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            :clearable="false"
            size="medium"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item style="margin-bottom: 15px!important;">
          <el-button type="primary" @click="onSubmit('formInline')" size="medium" icon="el-icon-search" plain>查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table :data="pendinglist" :resizable="false" header-row-class-name="table-top" :row-class-name="tableRowClassName"
        @sort-change="changeTableSort" style="width: 100%">
        <el-table-column fixed prop="xmbzNo" label="后台单号" align="center">
          <template slot-scope="scope" min-width="150px">
            <span>{{ scope.row.xmbzNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="配送时间" :sortable="'deliveryTimeSort'" align="center" prop="deliveryStartTime" min-width="90">
          <template slot-scope="scope">
            <span v-if="scope.row.deliveryStartTime == ''">立即配送</span>
            <span v-if="scope.row.deliveryStartTime !== ''" style="display: flex;flex-direction: column;">
              <span>{{ scope.row.deliveryStartTime.slice(0,10) }}</span>
              <span>{{ scope.row.deliveryStartTime.slice(11,16) }}~{{ scope.row.deliveryEndTime.slice(11,16) }}</span>
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="平台单号" prop="platformOrderId" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.platformOrderId }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="下单时间" :sortable="'orderTimeSort'" align="center" prop="orderTime" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.orderTime.slice(5,16) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货人" prop="receiverName" align="center" min-width="50">
          <template slot-scope="scope">
            <span>{{ scope.row.receiverName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="receiverPhone" align="center" min-width="50">
          <template slot-scope="scope">
            <span>{{ scope.row.receiverPhone }}</span>
          </template><strong></strong>
        </el-table-column>
        <el-table-column label="订单状态" prop="statusName" align="center" min-width="55">
          <template slot-scope="scope">
            <span>{{ scope.row.statusName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="配送地址" prop="receiverAddress" align="center" min-width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.receiverAddress }}</span>
          </template>
        </el-table-column>
        <el-table-column label="说明" align="center" min-width="110px">
          <template slot-scope="scope">
            <div class="el-col-primary dangerbutton" v-if="scope.row.replaceCake == 1 ? true : false">蛋糕原料缺失</div>
            <!-- <div class="el-col-primary mainbutton" v-if="scope.row.replaceDeliveryTime  == 1 ? true : false" style="margin-top: 5px;">运力紧张</div> -->
            <div class="el-col-primary warnbutton"  v-if="scope.row.refundMark == '平台退款中'">平台退款中</div>
          </template>
        </el-table-column>
        <el-table-column label="渠道" prop="channelName" align="center" min-width="53px">
          <template slot-scope="scope">
            <span>{{ scope.row.channelName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="城市" prop="deptName" align="center" min-width="45px">
          <template slot-scope="scope">
            <span>{{ scope.row.deptName }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column
          label="商品名称"
          prop=""
          align="center"
          width="180"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.channelName }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="客服备注" prop="customerServiceNotes" align="center">
          <template slot-scope="scope">
            <span style="color: red;">{{ scope.row.customerServiceNotes }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付金额" prop="totalPrice" align="center" min-width="53px">
          <template slot-scope="scope">
            <span>{{ (scope.row.totalPrice/100).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="left" min-width="48">
          <template slot-scope="scope" class="pendingLog">
            <i class="el-icon-edit" @mouseenter="aditenterColor(scope.$index, scope.row)" @mouseleave="aditleaveColor(scope.$index, scope.row)"
              :class="scope.$index == aditFlag ? 'active':'buttoncolor'" @click="handleEdit(scope.$index, scope.row)"
              style="cursor: pointer!important;">编辑</i>
            <br>
            <i class="el-icon-mobile" @mouseenter="dateenterColor(scope.$index, scope.row)" @mouseleave="dateleaveColor(scope.$index, scope.row)"
              :class="scope.$index == dateFlag ? 'active':'buttoncolor'" style="cursor: pointer!important;" @click="handleOrderLog(scope.row)">日志</i>
            <br>
            <i class="el-icon-view" @mouseenter="viewenterColor(scope.$index, scope.row)" @mouseleave="viewleaveColor(scope.$index, scope.row)"
              :class="scope.$index == viewFlag ? 'active':'buttoncolor'" style="cursor: pointer!important;" @click="handleViewLog(scope.$index, scope.row)">查看</i>
            <br>
            <i @mouseenter="SMSenterColor(scope.$index, scope.row)" @mouseleave="SMSleaveColor(scope.$index, scope.row)"
              :class="scope.$index == SMSFlag ? 'active':'buttoncolor'" style="cursor: pointer!important;font-style: normal" @click="handleSMS(scope.$index, scope.row)">短信记录</i>
            <!-- <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
             <el-button size="mini" class="el-icon-mobile" @click="handleEdit(scope.$index, scope.row)">日志</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="formInline.page" :limit.sync="formInline.size"
        @pagination="getList" />
    </div>
    <el-dialog title="日志" :visible.sync="LogFormVisible" width="width:400px">
      <div class="radio">显示方式：
        <el-radio-group v-model="reverse">
          <el-radio :label="true">倒序</el-radio>
          <el-radio :label="false">正序</el-radio>
        </el-radio-group>
      </div>
      <el-timeline :reverse="reverse">
        <el-timeline-item v-for="(activity, index) in getOrderOperateLogList" :key="index" :icon="activity.icon" :type="activity.type"
          :color="activity.color" :size="activity.size" :timestamp="activity.createTime">
          <h5>{{activity.operator}}</h5>
          <h4 v-html="activity.action">{{activity.action}}</h4>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
  import {
    orderList, // 查询
    forceUnlock, // 强制解锁
    startUpdate, //开始修改
    getOrderOperateLog, // 订单日志
    add0rderOperateLog, //添加订单操作日志
  } from '@/api/pending'
  import {
    citySelect, // 城市
    getOrderChannelList, // 渠道
    getOrderChannelTypeList, // 渠道类别列表
  } from '@/api/createOrder';
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  export default {
    components: {
      Pagination,
    },
    data() {
      var checkPhone = (rule, value, callback) => {
        setTimeout(() => {
          if (value !== '') {
            if (!Number.isInteger(value)) {
              this.formInline.receiverPhone = value.trim();
              callback(new Error('请输入数字值'));
            } else {
              if (value.toString().length !== 11) {
                callback(new Error('号码长度应为11位'));
              } else {
                callback();
              }
            }
          }
        }, 1000);
      }
      return {
        total: 0,
        deptId: '',
        deptName: '',
        formInline: {
          deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content, // 城市id
          xmbzNo: '', // 后台单号
          platformOrderId: '', // 平台单号
          status: 1,
          channelType: '', // 渠道类别
          select: '配送时间',
          channel: '', // 渠道
          receiverPhone: '', // 手机号
          deliveryStartTime: '', // 配送开始时间
          deliveryEndTime: '', // 配送结束时间
          orderTimeSort: 0, // 下单时间排序
          deliveryTimeSort: 0, // 配送时间排序
          page: 1,
          limit: 10,
          size: 10
        },
        pickerOptions:{
          onPick: (obj) => {
            this.pickerMinDate = new Date(obj.minDate).getTime();
          },
          disabledDate:(time)=> {
            if (this.pickerMinDate) {
              const day1 =  31 * 24 * 3600 * 1000;
              let maxTime = this.pickerMinDate + day1;
              let minTime = this.pickerMinDate - day1;
              return time.getTime() > maxTime || time.getTime()<minTime;
            }
          }
        },
        // pickerOptions: {
        //   shortcuts: [{
        //     text: '最近一周',
        //     onClick(picker) {
        //       const end = new Date();
        //       const start = new Date();
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        //       picker.$emit('pick', [start, end]);
        //     }
        //   }, {
        //     text: '最近一个月',
        //     onClick(picker) {
        //       const end = new Date();
        //       const start = new Date();
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        //       picker.$emit('pick', [start, end]);
        //     }
        //   }, {
        //     text: '最近三个月',
        //     onClick(picker) {
        //       const end = new Date();
        //       const start = new Date();
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        //       picker.$emit('pick', [start, end]);
        //     }
        //   }]
        // },
        channerllist: '', //渠道
        pendinglist: [],
        Loading: true,
        cityId: '',
        cityselect: "", // 城市获取列表
        channelTypellist: '', // 渠道类别列表
        getChannelList: { // 渠道列表
          parentId: ''
        },
        startUpdateList: {
          //开始修改列表
          orderId: 1
        },
        timerlist: null,
        getOrderOperateLogList: [],
        LogFormVisible: false,
        reverse: false,
        aditFlag: null, // 编辑按钮划进划出
        dateFlag: null, // 日志按钮划进划出
        viewFlag: null, // 查看按钮划进划出
        SMSFlag: null, // 短信记录划进划出
        authsList:["在线组", "PHONE", "ORDER"],
        timeValue: [], // 查询时间值
        timeValueFlag: false, // 查询时间是否大于31天标记
      }
    },
    created() {
      this.deptName = JSON.parse(window.localStorage.getItem("saber-areaname")).content;
      this.formInline.deptId = JSON.parse(window.localStorage.getItem("saber-areaId")).content;
      this.cityId = JSON.parse(window.localStorage.getItem("saber-areaId")).content;
      this.getDeliveryTime();
      this.getList();
      window.addEventListener("keydown",this.keyupEnter);
    },
    watch: {
      // pendinglist() {
      //   // console.log(this.timerlist, 'destory')
      //   // console.log('0990909')
      //   this.timer(); // 刷单
      // },
      'deptName'() {
        window.localStorage.setItem('deptName',this.deptName);
      },
      'LogFormVisible'() {
        if(this.LogFormVisible) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      }
    },
    mounted() {
      const _this = this;
      // 监听是否在当前页，并置为已读
      document.addEventListener("visibilitychange", function () {
        if (!document.hidden) {   //处于当前页面
          if((window.localStorage.getItem("routerFlag") === 'true') && (_this.$route.path.indexOf('Pending-orders') > -1)) {
            _this.getList();
            setTimeout(() => {
              window.localStorage.setItem('routerFlag', '');
              window.localStorage.setItem('routerFlag', false);
            },1000)
            // console.log(typeof window.localStorage.getItem("routerFlag"),'document.URL',document.URL,window.localStorage.getItem("routerFlag"))
          }
        }
      });
      // 城市
      citySelect(this.cityLi).then(res => {
        this.cityselect = res.data.data;
      }),
      // 渠道类别列表
      getOrderChannelTypeList().then(res => {
        this.channelTypellist = res.data.data;
      })
    },
    methods: {
      // 获取城市
      handleCity(data) {
        // console.log(data,'data')
        if (data) {
          this.deptName = data.label;
          this.formInline.deptId = data.value;
        } else {
          this.formInline.deptId = JSON.parse(window.localStorage.getItem("saber-areaId")).content;
          this.deptName = JSON.parse(window.localStorage.getItem("saber-areaname")).content;
        }

      },
      onSubmit() {
        this.formInline.page = 1;
        this.getList()
      },
      // 查询列表
      getList() {
        this.queryTime();
        if(!this.timeValueFlag) {
          this.Loading = true;
          orderList(this.formInline).then(res => {
            this.total = res.data.data.total
            this.pendinglist = res.data.data.rows
            // this.pendinglist.forEach(item => {
            //   item.customerServiceNotes = unescape(item.customerServiceNotes)
            // })
            // console.log('res',res.data.data)
            this.pendinglist.forEach((item, index) => {
              this.pendinglist[index].getHour = this.getHour(this.pendinglist[index].deliveryEndTime).toFixed(2)
              // console.log(this.pendinglist[index].getHour,'this.pendinglist[index].getHour')
              if (this.pendinglist[index].getHour > 3) {
                // console.log(this.pendinglist[index].getHour, '>3')
                this.pendinglist[index].getHour = true
              } else if (this.pendinglist[index].getHour < 3) {
                // console.log(this.pendinglist[index].getHour,'<3') // data00000
                this.pendinglist[index].getHour = false
              } else if (this.pendinglist[index].getHour.toString() === 'NaN') {
                // console.log('/3')
                this.pendinglist[index].getHour = true
              }
            })
            setTimeout(() => {
              this.Loading = false;
            }, 0.5 * 1000);
          })
        }
      },
      // 点击编辑，打开详情
      handleEdit(index, row) {
        var authority = JSON.parse(window.localStorage.getItem("saber-userInfo")).content.authority;
        this.startUpdateList.orderId = row.xmbzNo
        let orderId = row.id
        startUpdate(this.startUpdateList).then(res => {
          if (res.data.success == true) {
            let type = 98;
            this.add0rderInquiry(orderId,type); // 解锁日志
            window.open(href, '_blank');
          } else if (res.data.success == false) {
          var authorityArr = authority.split(',');
          if (authorityArr.length > 1) { //多角色
            const auths = this.dealData(authorityArr);
            this.authsList.forEach(p => {
              auths.map(c => {
                if (p === c.value) {
                  c.checked = false;
                }
              })
            });
            const endData = auths.filter(item => item.checked);
            if (endData.length >=1) {
              this.$confirm("是否需要强制解锁此订单?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(() => {
                forceUnlock(this.startUpdateList).then(res => {
                  if (res.data.code == 200) {
                    let type = 100;
                    this.add0rderInquiry(orderId,type); // 解锁日志
                    this.$message({
                      type: "success",
                      message: "解锁成功!"
                    });
                    window.open(href, '_blank');
                  }
                });
              }).catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消解锁成功"
                })
              })
            } else {
              this.$message({
                type: 'warning',
                message: '订单已被锁定'
              })

            }
          } else { //单角色
            if (authority == 'ORDER' || authority == '在线组' || authority == 'PHONE') {
              this.$message({
                type: 'warning',
                message: '订单已被锁定'
              })
            } else {
              this.$confirm("是否需要强制解锁此订单?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(() => {
                forceUnlock(this.startUpdateList).then(res => {
                  if (res.data.code == 200) {
                    let type = 100;
                    this.add0rderInquiry(orderId,type); // 解锁日志
                    this.$message({
                      type: "success",
                      message: "解锁成功!"
                    });
                    window.open(href, '_blank');
                  }
                });
              }).catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消解锁成功"
                })
              })
            }
          }

          }
        }).catch(error => {
          console.log('333', error)
        });
        const {
          href
        } = this.$router.resolve({
          // path: `/orderManage/Inquiry-order`,
          path: `/orderdetail`,
          query: {
            id: row.id,
            cityId: row.deptId,
            deptName: row.deptName,
            kind: 'Pending-orders',
            // paperName: this.paperName,
          }
        });
      },
      // 紧急单颜色变化
      tableRowClassName({
        row
      }) {
        // console.log(row.getHour,row.id,'row')
        if (row.getHour === false) {
          // console.log('false')
          return 'warning-row';
        }
        return '';
      },

      dealData(authority) {
        const newArr = [];
        authority.forEach(item => {
          newArr.push({
            checked: true,
            value: item
          })
        })
        return newArr;
      },
      // 编辑订单
      handleOrderLog(item) {
         this.reverse=false;
        this.LogFormVisible = true;
        getOrderOperateLog({
          orderId: item.id
        }).then(res => {
          // 订单日志
          console.log("工单日志", res.data.data);
          this.getOrderOperateLogList = res.data.data;
        });
      },
      // 计算时间差
      getHour(endTime) {
        let nowYear = new Date().getFullYear()
        let nowMonth = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() +
          1);
        let nowDate = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
        let nowHours = new Date().getHours() < 10 ? "0" + new Date().getHours() : new Date().getHours();
        let nowMinutes = new Date().getMinutes() < 10 ? "0" + new Date().getMinutes() : new Date().getMinutes();
        // console.log(e.currentTarget.dataset.time,nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes)
        let nowTime = nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes
        let s1 = new Date(endTime.replace(/-/g, '/'));
        // console.log('s1',s1)
        let s2 = new Date(nowTime.replace(/-/g, '/'));
        let ms = Math.abs(s1.getTime() - s2.getTime());
        let getHour = ms / 1000 / 60 / 60;
        // console.log('getHour',getHour)
        return getHour
      },
      // 选择渠道类型
      getchannelTypeId(e) {
        // 渠道列表接口
        this.getChannelList.parentId = e.currentTarget.dataset.id
        // console.log('e.currentTarget.dataset.id',e.currentTarget.dataset.id)
        // 渠道列表接口
        getOrderChannelList(this.getChannelList).then(res => {
          let result = res.data.data;
          result.forEach(item => {
            this.channerllist = result;
            if (this.formInline.channel !== undefined) {
              if (item.channelKey == this.formInline.channel) {
                this.channerllist = result;
              } else {
                this.channerllist = result;
                this.formInline.channel = '';
              }
            }
          })
        })
      },
      // 刷单
      timer() {
        if (this.timerlist !== null) {
          // console.log('this.timerlist',this.timerlist)
          clearInterval(this.timerlist)
        }
        this.timerlist = setInterval(() => {
          this.getList();
        }, 10000)
      },
      // 排序
      changeTableSort(column) {
        if (column.prop === 'orderTime' && column.order === 'ascending') {
          this.formInline.orderTimeSort = 1;
          this.formInline.deliveryTimeSort = '';
          this.getList();
        } else if (column.prop === 'orderTime' && column.order === 'descending') {
          this.formInline.orderTimeSort = 2;
          this.formInline.deliveryTimeSort = '';
          this.getList();
        } else if (column.prop === 'deliveryStartTime' && column.order === 'ascending') {
          this.formInline.deliveryTimeSort = 1;
          this.formInline.orderTimeSort = '';
          this.getList();
        } else if (column.prop === 'deliveryStartTime' && column.order === 'descending') {
          this.formInline.deliveryTimeSort = 2;
          this.formInline.orderTimeSort = '';
          this.getList();
        }
      },
      // 操作按钮划进
      aditenterColor(index, row) {
        this.aditFlag = index;
      },
      // 操作按钮划出
      aditleaveColor(index, row) {
        this.aditFlag = null;
      },
      // 操作按钮划进
      dateenterColor(index, row) {
        this.dateFlag = index;
      },
      // 操作按钮划出
      dateleaveColor(index, row) {
        this.dateFlag = null;
      },
      // 操作按钮划进
      viewenterColor(index, row) {
        this.viewFlag = index;
      },
      // 操作按钮划出
      viewleaveColor(index, row) {
        this.viewFlag = null;
      },
      // 短信记录按钮划进
      SMSenterColor(index, row) {
        this.SMSFlag = index;
      },
      // 短信记录按钮划出
      SMSleaveColor(index, row) {
        this.SMSFlag = null;
      },
      // 查看订单
      handleViewLog(index,row) {
        let newUrl = this.$router.resolve({
          path: "/viewOrdInfor",
          query: {
            id: row.id,
            cityId: row.deptId,
            deptName: row.deptName,
            kind: 'Pending-orders',
            // paperName: this.paperName,
          }
        });
        let type = 101;
        let orderId = row.id;
        this.add0rderInquiry(orderId,type);
        window.open(newUrl.href, "_blank");
      },
      // 设置默认查询日期
      getDeliveryTime() {
        //前一天设定的日期时间
        let d = new Date
        let year1,month1,day1
        [year1,month1,day1] = [d.getFullYear(),d.getMonth(),d.getDate()];
        let date1 = new Date(year1,month1,day1,0);
        let nowMonth1 = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() +
          1);
        let nowDate1 = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
        let deliveryStartTime = date1.getFullYear() + '-' + nowMonth1 + '-' + nowDate1 + ' ' + '00:00:00';
        this.timeValue.unshift(date1);
        this.formInline.deliveryStartTime = deliveryStartTime;
        //当前设定的日期时间
        let year2,month2,day2;
        d.setTime(d.getTime()+7*24*60*60*1000+59*60);
        [year2,month2,day2] = [d.getFullYear(),d.getMonth(),d.getDate()];
        let date2 = new Date(year2, month2, day2,23,59,59);
        let nowMonth2 = (date2.getMonth() + 1) < 10 ? "0" + (date2.getMonth() + 1) : (date2.getMonth() +
          1);
        let nowDate2 = date2.getDate() < 10 ? "0" + date2.getDate() : date2.getDate();
        let deliveryEndTime = date2.getFullYear() + '-' + nowMonth2 + '-' + nowDate2 + ' ' + '23:59:59';
        this.timeValue.push(date2);
        this.formInline.deliveryEndTime = deliveryEndTime;
        // console.log('this.timeValue',this.timeValue,'deliveryStartTime',deliveryStartTime,deliveryEndTime)
      },
      // 转换成标准时间（开始）
      changeStartTime(deliveryTime) {
        let date1 = new Date(deliveryTime);
        let nowMonth1 = (date1.getMonth() + 1) < 10 ? "0" + (date1.getMonth() + 1) : (date1.getMonth() +
          1);
        let nowDate1 = date1.getDate() < 10 ? "0" + date1.getDate() : date1.getDate();
        return deliveryTime = date1.getFullYear() + '-' + nowMonth1 + '-' + nowDate1 + ' ' + '00:00:00';
      },
      // 转换成标准时间（结束）
      changeEndTime(deliveryTime) {
        let date1 = new Date(deliveryTime);
        let nowMonth1 = (date1.getMonth() + 1) < 10 ? "0" + (date1.getMonth() + 1) : (date1.getMonth() +
          1);
        let nowDate1 = date1.getDate() < 10 ? "0" + date1.getDate() : date1.getDate();
        return deliveryTime = date1.getFullYear() + '-' + nowMonth1 + '-' + nowDate1 + ' ' + '23:59:59';
      },
      // 查询配送时间
      queryTime() {
        if (this.formInline.select === '下单时间') {
          if(this.timeValue[0].length === undefined) {
            this.formInline.orderTimeStart = this.changeStartTime(this.timeValue[0]);
            this.formInline.orderTimeEnd = this.changeEndTime(this.timeValue[1]);
          } else {
            this.formInline.orderTimeStart = this.timeValue[0] + ':00';
            this.formInline.orderTimeEnd = this.timeValue[1] + ':59';
          }
          this.isgreaterThan(this.formInline.orderTimeStart,this.formInline.orderTimeEnd)
          this.formInline.deliveryStartTime = '';
          this.formInline.deliveryEndTime = '';
        } else if (this.formInline.select === '配送时间') {
          // console.log('this.timeValue[0]',this.timeValue[0])
          if(this.timeValue[0].length === undefined) {
            this.formInline.deliveryStartTime = this.changeStartTime(this.timeValue[0]);
            this.formInline.deliveryEndTime = this.changeEndTime(this.timeValue[1]);
          } else {
            this.formInline.deliveryStartTime = this.timeValue[0] + ':00';
            this.formInline.deliveryEndTime = this.timeValue[1] + ':59';
          }
          this.isgreaterThan(this.formInline.deliveryStartTime,this.formInline.deliveryEndTime)
          this.formInline.orderTimeStart = '';
          this.formInline.orderTimeEnd = '';
        } else {
          this.formInline.deliveryStartTime = '';
          this.formInline.deliveryEndTime = '';
          this.formInline.orderTimeStart = '';
          this.formInline.orderTimeEnd = '';
        }
      },
      // 判断是否大于31天
      isgreaterThan(time1,time2) {
        var data1 = Date.parse(time1.replace(/-/g,"/"));
        var data2 = Date.parse(time2.replace(/-/g,"/"));
        var datadiff = data2-data1;
        var time = 31*24*60*60*1000;     
        if(time1.length>0 && time2.length>0){
          if(datadiff<0||datadiff>time){
            // console.log("开始时间应小于结束时间并且间隔小于31天，请检查!",data1,data2,datadiff);
            this.$message.warning("时间间隔不可超过31天");
            return this.timeValueFlag = true;
          } else {
            return this.timeValueFlag = false;
          }
        } 
      },
      // 查询短信记录
      handleSMS(index,row) {
        let newUrl = this.$router.resolve({
          path: "/SMSrecord",
          query: {
            id: row.id,
            cityId: row.deptId,
            deptName: row.deptName,
            kind: 'SMS-orders',
            // paperName: this.paperName,
          }
        });
        window.open(newUrl.href, "_blank");
      },
      // 添加订单操作日志
      add0rderInquiry(orderId,type) {
        let queryOrder = {
          orderId,
          type,
          orderType: 1,
          workType: 0
        }
        add0rderOperateLog(queryOrder).then(res => {
          console.log('res',res.data.code)
        })
      },
      // 电话号码限制
      filterPhone(val) {
        // console.log('va',val)
        this.formInline.receiverPhone = val.replace(/[^\d]/g,'');
      },
      // 禁止输入空格
      keydown(event) {
        if(event.keyCode == 32) {
          event.returnValue = false;
        }
        if(event.keyCode == 13) {
          this.$refs['channelTypeRef'].blur();
          this.$refs['channelRef'].blur();
          event.returnValue = false;
        }
      },
      // 回车事件
      keyupEnter(){
        if(window.event.keyCode == 13 ){
          this.onSubmit();// 查询事件
        }
      },
      selectBlur(e) {
        if(e.keyCode == 13) {
          this.$refs['deptRef'].blur();
          this.$refs['selectRef'].blur();
          e.returnValue = false;
        }
      }
    },
    beforeDestory() {
      // console.log(this.timerlist,'destory')
      clearInterval(this.timerlist);
      this.timerlist = null;
    },
    destroyed() {
      clearTimeout(this.timerlist);
      this.timerlist = null;
      window.removeEventListener("keydown",this.keyupEnter);
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    deactivated() {
      window.removeEventListener("keydown",this.keyupEnter);
    }
  }
</script>

<style lang="scss">
  .red {
    color: #FF0000;
  }

  .app-pending {
    padding-right: 8px;
    .top-container {
      padding: 20px 10px 10px 20px;

      .demo-form-inline {
        display: inline-block;
      }

      .el-form-item {
        margin-bottom: 20px !important;
      }
    }

    .table-container {
      padding-left: 10px;

      .table-top {
        font-size: 13px;
        th {
          padding: 5px 1px;
          .cell {
            padding: 0;
          }
        }
      }

      .el-table {
        .el-col-primary {
          margin: 0;
          padding: 2px 2px;
          font-size: 12px;
          font-weight: 400;
          border-radius: 4px;
          width: 78%;
          &.mainbutton {
            background: #ecf5ff;
            color: #409eff;
            border: 1px solid #b3d8ff;
          }

          &.dangerbutton {
            background: #fef0f0;
            color: #f56c6c;
            border: 1px solid #fbc4c4;
          }

          &.warnbutton {
            background: #fdf6ec;
            color: #e6a23c;
            border: 1px solid  #f5dab1;
          }
        }
      }

      .el-table__row {
        td {
          padding: 5px 1px;
          font-size: 13px;
          font-weight: 600;
          // font-size: 12px;
          border-right: 0;
          .cell {
            padding: 0;
            line-height: 20px;
            span {
              margin-left: 0;
            }
          }
        }
      }

      .active {
        color: #409eff;
        font-size: 13px;
        font-weight: 600;
      }

      .buttoncolor {
        color: #000;
        font-size: 13px;
        font-weight: 600;
      }

      .warning-row {
        background: oldlace;
        color: #e6a23c;
      }
    }
  }
  .el-date-range-picker .el-picker-panel__footer .el-button--text span {
    display: none;
  }
</style>
